﻿using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Luminji.Core.Silverlight.Json
{
    public class JsonHelper
    {
        public string ModelToJson<T>(T t)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(t.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.WriteObject(stream, t);
                var json = stream.ToArray();
                return Encoding.UTF8.GetString(json, 0, json.Length);
            }
        }

        public TOut JsonToModel<TOut>(string json)
        {
            TOut obj = Activator.CreateInstance<TOut>();
            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (TOut)serializer.ReadObject(stream);
            }
        }

    }
}
